<?php
/*
 *@Author 	: İbrahim Halil SANDUVAÇ
 *@Date 	: 14.06.2011 - 
 */
 
include_once "config.php";

include_once "mysql.class.php";

class yp extends MySQL{
	
	/*
	 *@function __construct : constuction fn
	 *@access : public
	 *@param Bool $start_session=true
	 *@param Bool $connect_mysql=true
	 *@param Bool $select_db=true
	 *@param String $config_file="config.php"
	 */
	public function __construct($start_session = true, $connect_mysql = true, $select_db = true, $config_file="config.php"){
		
		date_default_timezone_set('Europe/Istanbul');
		
		if($start_session == true){
			session_start();	
		}
		if($connect_mysql == true){
			$this->connect($this->get_config_info($config_file,1),$this->get_config_info($config_file,2),$this->get_config_info($config_file,3));
			if($select_db)
				$this->select_db($this->get_config_info($config_file,4));
		}
	}
	
	######################### GENERAL FUNCTIONS #########################
	
	/*
	 *@function set_message : sets a yp message
	 *@access : public
	 *@param String $message_name
	 *@param String $message
	 */
	public function set_message($message_name, $message){
		if(!session_is_registered("ypMessage"))
			session_register("ypMessage");
		$_SESSION["ypMessage"][$message_name] = $message;
	}
	
	/*
	 *@function get_message : gets yp message
	 *@access : public
	 *@param String $message_name
	 *@param Bool $release=false
	 *@return String message
	 */
	public function get_message($message_name, $release=false){
		if(session_is_registered("ypMessage"))
		{
			if($_SESSION["ypMessage"][$message_name] == false)
				return false;
			else{
				$res = $_SESSION["ypMessage"][$message_name];
				if($release == true)
					$_SESSION["ypMessage"][$message_name] = false;
				return $res;
			}
		}
		else
			return false;
	}
	
	/*
	 * @function curr_date : returns current date
	 * @acccess : public
	 * @return String : current date
	 */
	public function curr_date()
	{
		return date("Y-m-d H:i:s");	
	}
	
	/*
	 * @function go : redirects an adress
	 * @acccess : public
	 * @param String $adress : redirect adress
	 */
	public function go($adress)
	{
		?>
		<script>window.location='<?php echo $adress;?>';</script>
        <?php	
	}	
	
	/*
	 * @function reverse_date : reforms date which is get by current_date()
	 * @access : public
	 * @param String $date : date
	 * @param String $seperator="-" : date seperator = 10-06-2011
	 * @return String : date
	 */
	public function reverse_date($date, $seperator="-"){
		
		$slice1 = explode(" ", $date);
		$slice2 = explode("-",$slice1[0]);
		
		return	$slice2[2].$seperator.$slice2[1].$seperator.$slice2[0]." ".$slice1[1];
		
	}
	
	/*
	 * @function db_add : insert data to databese
	 * @access : public 
	 * @param String $table : table_name
	 * @param String $values : datas
	 * @return : mysql_query
	 */
	public function db_add($table, $values){
		
		return $this->query("INSERT INTO $table VALUES($values)");
		
	}
	
	/*
	 * @function db_del : delete data from databese
	 * @access : public 
	 * @param String $table : table_name
	 * @param Mixed $id : id(s)
	 * @return : mysql_query
	 */
	public function db_del($table, $id){
		
		return $this->query("DELETE FROM $table WHERE id IN($id)");
		
	}
	
	/*
	 * @function db_update : update data on databese
	 * @access : public 
	 * @param String $table : table_name
	 * @param String $update : updates
	 * @param String $where : where
	 * @return : mysql_query
	 */
	public function db_update($table, $update, $where){
		
		return $this->query("UPDATE $table SET $update WHERE $where");
		
	}
	
	/*
	 *@function db_get : get datas from database
	 *@access : public
	 *@param String $select_name : selected datas
	 *@param String $table : table
	 *@param String $where : where
	 *@param String $extras=NULL : extra
	 *@return : mysql_query
	  */
	public function db_get($select_name, $table, $where=1, $extras=NULL){
		
		return $this->query("SELECT $select_name FROM $table WHERE $where $extras");
		
	}
	
	/*
	 *@function get_config_info : get config info
	 *@access : public
	 *@param String $config_file : config file's address
	 *@param Int $order : variable order
	 *@return String : var value
	 */
	public function get_config_info($config_file, $order){
		$file = @fopen($config_file, "r");
		
		$contents = fread($file, filesize($config_file));
		
		$contents = str_replace("<?php","",str_replace("?>","",$contents));
		
		$parts = explode(";",$contents);
		
		$second_parts = explode(",",$parts[$order-1]);
		
		return str_replace(array("'",')'),array("",""),$second_parts[1]);
	}
	
	/*
	 *@function change_config_file : changes variables in the config file
	 *@access : public
	 *@param String $config_file : config file's address
	 *@param Int $order : variable order
	 *@param String $value : new value
	 */
	public function change_config_file($config_file, $order, $value){
		$file = @fopen($config_file, "r");
		
		$contents = fread($file, filesize($config_file));
		
		$contents = str_replace("<?php","",str_replace("?>","",$contents));
		
		$parts = explode(";",$contents);
		
		$second_parts = explode(",",$parts[$order-1]);
		
		$second_parts[1] = "'".$value."')";
		
		$second_parts = implode(",",$second_parts);
		
		for($x = 1; $x < count($parts); $x++){
			if($x == $order)
				$parts[$x-1] = $second_parts;
		}
		
		$parts = implode(";",$parts);
		
		$contents = "<?php".$parts."?>";
		
		fclose($file);
		
		unlink($config_file);
		
		$file = @fopen($config_file,"a+");
		
		fwrite($file, $contents);
		
		fclose($file);
	}
	
	######################### CREATION FUNCTIONS #########################
	
	/*
	 *@function create_yp_db : create database named san-panel
	 *@access : public
	 *@param String $db_name
	 */
	public function create_yp_db($db_name){
		$this->query("CREATE DATABASE  `$db_name` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;");
	}
	
	/*
	 *@function create_tables : create tables on san-panel db
	 *@access : public 
	 *@param Bool $users : create table named users
	 *@param Bool $settings : create table named settings
	 */
	public function create_tables($users=true, $settings=true, $posts=true){
		if($users){
			$this->query("CREATE TABLE `users` (
`id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 64 ) NOT NULL ,
`password` VARCHAR( 32 ) NOT NULL ,
`name` VARCHAR( 255 ) NOT NULL ,
`authority` SMALLINT( 3 ) NOT NULL ,
`email` VARCHAR( 255 ) NOT NULL ,
`block` SMALLINT( 1 ) NOT NULL ,
`reg_date` DATETIME NOT NULL ,
`last_access_date` DATETIME NOT NULL
) ENGINE = INNODB;");
		}
		
		if($settings){
			$this->query("CREATE TABLE  `settings` (`id` INT( 4 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,`value` VARCHAR( 255 ) NOT NULL) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_bin;");
			$this->query("INSERT INTO `settings` (`id`, `value`) VALUES (NULL, 'top') ;INSERT INTO `settings` (`id`, `value`) VALUES (NULL, '1'), (NULL, '10'), (NULL, '2'), (NULL, '1'), (NULL, 'top'), (NULL, '0');");
		}
		
		if($posts){
			$this->query("CREATE TABLE `posts` (`id` INT(9) NOT NULL AUTO_INCREMENT PRIMARY KEY, `title` TEXT NOT NULL, `content` LONGTEXT NOT NULL, `author` INT(5) NOT NULL, `type` VARCHAR(25) NOT NULL, `category` INT(5) NOT NULL, `date` DATETIME NOT NULL, `modified_date` DATETIME NOT NULL, `orders` INT(9) NOT NULL, `comment_block` SMALLINT(1) NOT NULL, `block` SMALLINT(1) NOT NULL) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_bin;");
			$this->query("ALTER TABLE  `settings` COMMENT =  '1 = add_new_post_order'; ALTER TABLE  `posts` ADD  `abstract` LONGTEXT NOT NULL AFTER  `content`");
		}
		
		if($authorities){
			$this->query("CREATE TABLE `authorities` (`id` INT(3) NOT NULL AUTO_INCREMENT PRIMARY KEY, `authority_name` VARCHAR(64) NOT NULL, `privileges` VARCHAR(64) NOT NULL) ENGINE = InnoDB COMMENT = 'opp opd ope cp lp mpp mvp lp pp rp up pp sp'; INSERT INTO `authorities` (`id`, `authority_name`, `privileges`) VALUES (NULL, 'admin', '1111111111111'); INSERT INTO `authorities` (`id`, `authority_name`, `privileges`) VALUES (NULL, 'none_authority', '0000000000000');");
		}
	}
	
	######################### USER FUNCTIONS #########################
	
	/*
	 * @function user_login : user login
	 * @access : public
	 * @param String $username : username
	 * @param String $password : password
	 * @return Bool : user_loginned?
	 */
	public function	user_login($username,$password){
		
		$password = md5($password);
		
		$sql_user_login = $this->db_get("*","users","username='$username' AND password='$password' AND block=0");
		
		if($this->num_rows($sql_user_login) == false){
			return false;
		}
		else{
			session_register("current_user");	
			
			$_SESSION["current_user"] = $this->fetch_array($sql_user_login);
			
			$curr_date = $this->curr_date();
			
			$this->db_update("users","last_access_date='$curr_date'","id=".(int)$_SESSION['current_user']["id"]);
			
			return true;
		}
		
	}
	
	/*
	 * @function user_login : user login
	 * @access : public
	 * @param Int $id : user_id
	 * @return Bool : user_loginned?
	 */
	public function	user_login_just_id($id){
		
		$id = (int)$id;
		
		$sql_user_login = $this->db_get("*","users","id=$id AND block=0");
		
		if($this->num_rows($sql_user_login) == false){
			return false;
		}
		else{
			session_register("current_user");	
			
			$_SESSION["current_user"] = $this->fetch_array($sql_user_login);
			
			$curr_date = $this->curr_date();
			
			$this->db_update("users","last_access_date='$curr_date'","id=".(int)$_SESSION['current_user']["id"]);
			
			return true;
		}
		
	}
	
	/*
	 * @function user_logout : logout
	 * @access : public
	 */
	public function user_logout(){
				
		session_destroy();

	}
	
	/*
	 * @function user_login_check : checks user is loginned
	 * @access : public
	 * @return Bool 
	 */
	public function user_login_check(){
		if(session_is_registered("current_user"))	
			return true;
		else
			return false;
	}
	
	/*
	 * @function user_register : registers user
	 * @access : public
	 * @param String $username : username
	 * @param String $password : password
	 * @param String $name : name
	 * @param Int $authority : authority
	 * @param String $email : email
	 * @param Int $block : block
	 */
	public function user_register($username, $password, $name, $authority, $email, $block){
		
		$password = md5($password);
		$curr_date = $this->curr_date();
		
		$this->db_add("users", "null, '$username', '$password', '$name', $authority, '$email', $block, '$curr_date', '$curr_date'");		
		
	}
	
	######################### POST FUNCTIONS #########################
	
	/*
	 *@function new_order : gets new order number for an item
	 *@access : public
	 *@param String $table : item type(it is table name)
	 *@return Int new order
	 */
	public function new_order($table){
		$fetch_to = $this->fetch_array($this->query("SELECT value FROM settings WHERE id=1"));
		$to = $fetch_to["value"];
		
		if($to == "top"){
			return 1;
		}
		else{
			$fetch_get_order = $this->fetch_array($this->query("SELECT MAX(orders)+1 AS sira FROM $table"));
			
			if($fetch_get_order["sira"] == NULL)
				$fetch_get_order["sira"] = 1;
			return (int)$fetch_get_order["sira"];
		}
	}
	
	/*
	 *@function process_order : processes other items order
	 *@access : public
	 *@param Int $order
	 *@param String $table : table name
	 *@param Int $item_id=false
	 */
	public function process_order($order, $table, $item_id=false){
		$order = (int)$order;
		
		$fetch_max_order_number = $this->fetch_array($this->query("SELECT MAX(orders) AS sira FROM $table"));
		$max_order_number = $fetch_max_order_number["sira"];
		
		
		if($fetch_max_order_number != NULL){
			for($x = $max_order_number; $x >= $order; $x--){
				$new_order_number = $x+1;
				$sql_process_order = $this->query("UPDATE $table SET orders=$new_order_number WHERE orders=$x");
			}
		}
		if(!$item_id)
			$sql_process_new_order = $this->query("UPDATE $table SET orders=$order WHERE id=$item_id");
	}
	
	######################### PRIVILEGE FUNCTIONS #########################
	/*
	 *Own Post Procesing
	 *Other Post Delete
	 *Other Post Edit
	 *Comment Processing
	 *Link Proessing
	 *Media Photo Processing
	 *Media Video Processing
	 *Library Processing
	 *Page Processing
	 *RSS Processing
	 *
	 *User Processing
	 *Privilege Processing
	 *Settings Processing
	 */
	
	/*
	 *@function can_access_authority - check authority for access
	 *@access : public
	 *@param Int $for : privilege order
	 *@param Int $authority=true : authority id - for TRUE value it gets current user's authority
	 *@return Bool authority access
	 */
	public function can_access_authority($for, $authority=true){
		if($authority)
			$authority = (int)$_SESSION["current_user"]["authority"];
		else
			$authority = (int)$authority;
		
		$fetch_authority = $this->fetch_array($this->db_get("privileges","authorities","id=$authority"));
		
		$split_auth = str_split($fetch_authority["privileges"]);
		
		if($split_auth[$for + 1] == 1)
			return true;
		else
			return false;
	}
	
	/*
	 *@function can_access_block - check block for access
	 *@access : public
	 *@param Int $user_id=true : user id - for TRUE value it gets current user's block
	 *@return Bool block access
	 */
	public function can_access_block($user_id=true){
		if($user_id){
			if((int)$_SESSION["current_user"]["block"] == 0)	
				return true;
			else
				return false;			
		}
		else{
			$user_id = (int)$user_id;
			$fetch_user = $this->fetch_array($this->db_get("block","users","id=$user_id"));
			if((int)$fetch_user["block"] == 1)
				return false;
			else
				return true;
		}
	}
	
	/*
	 *@function can_access - check block and authority for access
	 *@access : public
	 *@param Int $for : authority order
	 *@param Int $user_id=true : user id - for TRUE value it gets current user
	 *@return Bool block access
	 */
	public function can_access($for, $user_id=true){
		if($user_id){
			if($for != "*" || $for != "all")
				$access_auth = $this->can_access_authority($for);
			else
				$access_auth = true;
			$access_block = $this->can_access_block();
			if($access_auth && $access_block)
				return true;
			else
				return false;
		}
		
		else{
			if($for != "*" || $for != "all"){
				$fetch_auth = $this->fetch_array($this->db_get("authority","users","id=$user_id"));	
				$authority_id = (int)$fetch_auth["authority"];
				$access_auth = $this->can_access_authority($for, $authority_id);
			}
			else
				$access_auth = true;
			$access_block = $this->can_access_block($user_id);
			if($access_auth && $access_block)
				return true;
			else
				return false;
		}
	}
	
	######################### SETTINGS FUNCTIONS #########################
	
	/*
	 *@function get_settings
	 *@access : public
	 *@param Int $setting_order - setting id
	 *@return String value
	 */
	public function get_setting($setting_order){
		$setting_order = (int)$setting_order;
		$fetch_get = $this->fetch_array($this->db_get("value","settings","id=".$setting_order));
		
		return $fetch_get["value"];
	}
	
	/*
	 *@function set_settings
	 *@access : public
	 *@param Int $setting_order - setting id
	 *@param String $new_value - new value
	 */
	public function set_setting($setting_order, $new_value){
		$setting_order = (int)$setting_order;
		
		$sql_set = $this->db_update("settings","value='$new_value'","id=".$setting_order);
	}
		
}


?>